package com.app.bimo.module_bookrack.mvp.ui.adapter;


import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;


import com.app.bimo.commonbusiness.util.Constant;
import com.app.bimo.commonbusiness.util.DataUtil;
import com.app.bimo.commonbusiness.util.GlideImagSetUtil;
import com.app.bimo.commonbusiness.util.RouterHub;
import com.app.bimo.commonbusiness.util.SystemUtil;
import com.app.bimo.commonbusiness.util.UiUtil;
import com.app.bimo.commonbusiness.view.recyclerview.RecycleAdapterImpl;
import com.app.bimo.commonbusiness.view.recyclerview.RecyclerViewHolder;
import com.app.bimo.library_db.SearchData;
import com.app.bimo.module_bookrack.R;
import com.bytedance.sdk.openadsdk.DownloadStatusController;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdDislike;
import com.bytedance.sdk.openadsdk.TTFeedAd;
import com.bytedance.sdk.openadsdk.TTImage;
import com.bytedance.sdk.openadsdk.TTNativeAd;

import java.util.ArrayList;
import java.util.List;

import androidx.constraintlayout.widget.ConstraintLayout;

public class BookrackSearchBookAdapter extends RecycleAdapterImpl<SearchData> {
    private String searchKey;
    public final static int LIST_TYPE = 1;
    public final static int AD_TYPR = 2;


    public BookrackSearchBookAdapter(Context context, List<SearchData> list) {
        super(list, context);
    }

    @Override
    public int getViewId(int position) {

        if (position == LIST_TYPE) {
            return R.layout.bookrack_adapter_search;
        } else {
            return R.layout.bookrack_home_adapter_search_ad;
        }
    }

    @Override
    public RecyclerViewHolder getHold(int id) {
        return new Hold(id, context);
    }


    public void setSearchKey(String searchKey) {
        this.searchKey = searchKey;
    }

    @Override
    public void initView(RecyclerViewHolder thold, int position) {
        final Hold hold = (Hold) thold;
        SearchData data = getItem(position);
        ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) hold.book.getLayoutParams();
        lp.width = SystemUtil.getImgW63(context);
        hold.book.setLayoutParams(lp);
        if (data.getAd() == null) {
            initNomalData(hold, data);
        } else {
            initAdData(hold, data, position);
        }

    }

    private void initAdData(Hold hold, SearchData data, int position) {
        TTFeedAd ad = data.getAd();
        if (ad == null) {
            return;
        }
        //可以被点击的view, 也可以把convertView放进来意味item可被点击
        List<View> clickViewList = new ArrayList<>();
        clickViewList.add(hold.itemView);
        //触发创意广告的view（点击下载或拨打电话）
        List<View> creativeViewList = new ArrayList<>();
        creativeViewList.add(hold.itemView);
        //如果需要点击图文区域也能进行下载或者拨打电话动作，请将图文区域的view传入
//            creativeViewList.add(convertView);
        //重要! 这个涉及到广告计费，必须正确调用。convertView必须使用ViewGroup。
        ad.registerViewForInteraction((ViewGroup) hold.itemView, clickViewList, creativeViewList, new TTNativeAd.AdInteractionListener() {
            @Override
            public void onAdClicked(View view, TTNativeAd ad) {
                if (ad != null) {
//                    TToast.show(mContext, "广告" + ad.getTitle() + "被点击");
                }
            }

            @Override
            public void onAdCreativeClick(View view, TTNativeAd ad) {
                if (ad != null) {
//                    TToast.show(mContext, "广告" + ad.getTitle() + "被创意按钮被点击");
                }
            }

            @Override
            public void onAdShow(TTNativeAd ad) {
                if (ad != null) {
//                    TToast.show(mContext, "广告" + ad.getTitle() + "展示");
                }
            }
        });
        hold.bookName.setText(ad.getTitle());

        hold.tv_listitem_ad_source1.setText(DataUtil.isEmpty(ad.getButtonText()) ? "立即体验" : ad.getButtonText());
        hold.tv_listitem_ad_source.setText(DataUtil.isEmpty(ad.getDescription()) ? "" : ad.getDescription());


        bindDislikeAction(hold, data, ad, hold.iv_listitem_dislike);
        TTImage icon = ad.getImageList().get(0);
        if (icon != null && icon.isValid()) {
            GlideImagSetUtil.loadImgRoundedCornersCenterCrop(icon.getImageUrl(), hold.book, SystemUtil.dip2px(context, 3));
        }
        View adCreativeButton = hold.itemView;
        switch (ad.getInteractionType()) {
            case TTAdConstant.INTERACTION_TYPE_DOWNLOAD:
                //如果初始化ttAdManager.createAdNative(getApplicationContext())没有传入activity 则需要在此传activity，否则影响使用Dislike逻辑
                if (context instanceof Activity) {
                    ad.setActivityForDownloadApp((Activity) context);
                }
                adCreativeButton.setVisibility(View.VISIBLE);
//                hold.mStopButton.setVisibility(View.VISIBLE);
//                hold.mRemoveButton.setVisibility(View.VISIBLE);
//                bindDownloadListener(adCreativeButton, adViewHolder, ad);
//                绑定下载状态控制器
//                bindDownLoadStatusController(adViewHolder, ad);
                break;
            case TTAdConstant.INTERACTION_TYPE_DIAL:
                adCreativeButton.setVisibility(View.VISIBLE);
//                adCreativeButton.setText("立即拨打");
//                hold.mStopButton.setVisibility(View.GONE);
//                hold.mRemoveButton.setVisibility(View.GONE);
                break;
            case TTAdConstant.INTERACTION_TYPE_LANDING_PAGE:
            case TTAdConstant.INTERACTION_TYPE_BROWSER:
//                    adCreativeButton.setVisibility(View.GONE);
                adCreativeButton.setVisibility(View.VISIBLE);
//                adCreativeButton.setText("查看详情");
//                hold.mStopButton.setVisibility(View.GONE);
//                hold.mRemoveButton.setVisibility(View.GONE);
                break;
            default:
                adCreativeButton.setVisibility(View.VISIBLE);
//                hold.mStopButton.setVisibility(View.GONE);
//                hold.mRemoveButton.setVisibility(View.GONE);
//                TToast.show(mContext, "交互类型异常");
        }
    }

    //接入网盟的dislike 逻辑，有助于提示广告精准投放度

    private void bindDislikeAction(Hold hold, SearchData bookData, TTNativeAd ad, View dislikeView) {
        final TTAdDislike ttAdDislike = ad.getDislikeDialog((Activity) context);
        if (ttAdDislike != null) {
            ttAdDislike.setDislikeInteractionCallback(new TTAdDislike.DislikeInteractionCallback() {
                @Override
                public void onSelected(int position, String value) {
                    int index = list.indexOf(bookData);
                    list.remove(index);
                    notifyItemRemoved(index + 1);
                }

                @Override
                public void onCancel() {

                }
            });
        }
        dislikeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ttAdDislike != null)
                    ttAdDislike.showDislikeDialog();
            }
        });
    }

    private void bindDownLoadStatusController(BookrackAdapter.Hold adViewHolder, final TTFeedAd ad) {
        final DownloadStatusController controller = ad.getDownloadStatusController();
//        adViewHolder.mStopButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (controller != null) {
//                    controller.changeDownloadStatus();
//                    TToast.show(mContext, "改变下载状态");
//                    Log.d(TAG, "改变下载状态");
//                }
//            }
//        });

//        adViewHolder.mRemoveButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (controller != null) {
//                    controller.cancelDownload();
//                    TToast.show(mContext, "取消下载");
//                    Log.d(TAG, "取消下载");
//                }
//            }
//        });
    }

    //    private void bindDownloadListener(final Button adCreativeButton, final Hold adViewHolder, TTFeedAd ad) {
//        TTAppDownloadListener downloadListener = new TTAppDownloadListener() {
//            @Override
//            public void onIdle() {
//                if (!isValid()) {
//                    return;
//                }
////                adCreativeButton.setText("开始下载");
////                adViewHolder.mStopButton.setText("开始下载");
//            }
//
//            @SuppressLint("SetTextI18n")
//            @Override
//            public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
//                if (!isValid()) {
//                    return;
//                }
//                if (totalBytes <= 0L) {
//                    adCreativeButton.setText("0%");
//                } else {
//                    adCreativeButton.setText((currBytes * 100 / totalBytes) + "%");
//                }
////                adViewHolder.mStopButton.setText("下载中");
//            }
//
//            @SuppressLint("SetTextI18n")
//            @Override
//            public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
//                if (!isValid()) {
//                    return;
//                }
//                if (totalBytes <= 0L) {
//                    adCreativeButton.setText("0%");
//                } else {
//                    adCreativeButton.setText((currBytes * 100 / totalBytes) + "%");
//                }
//                adViewHolder.mStopButton.setText("下载暂停");
//            }
//
//            @Override
//            public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
//                if (!isValid()) {
//                    return;
//                }
//                adCreativeButton.setText("重新下载");
//                adViewHolder.mStopButton.setText("重新下载");
//            }
//
//            @Override
//            public void onInstalled(String fileName, String appName) {
//                if (!isValid()) {
//                    return;
//                }
//                adCreativeButton.setText("点击打开");
//                adViewHolder.mStopButton.setText("点击打开");
//            }
//
//            @Override
//            public void onDownloadFinished(long totalBytes, String fileName, String appName) {
//                if (!isValid()) {
//                    return;
//                }
//                adCreativeButton.setText("点击安装");
//                adViewHolder.mStopButton.setText("点击安装");
//            }
//
//            @SuppressWarnings("BooleanMethodIsAlwaysInverted")
//            private boolean isValid() {
//                return mTTAppDownloadListenerMap.get(adViewHolder) == this;
//            }
//        };
//        //一个ViewHolder对应一个downloadListener, isValid判断当前ViewHolder绑定的listener是不是自己
//        ad.setDownloadListener(downloadListener); // 注册下载监听器
//        mTTAppDownloadListenerMap.put(adViewHolder, downloadListener);
//    }
    private void initNomalData(Hold hold, SearchData data) {

        GlideImagSetUtil.loadImgRoundedCornersCenterCrop(data.getCover(), hold.book, SystemUtil.dip2px(context, 3));
        String s;

        if (!DataUtil.isEmpty(searchKey)) {
            s = data.getNovelName().replaceAll(searchKey, "<font color='#38A6FE'>" + searchKey + "</font>");
        } else {
            s = data.getNovelName();
        }
        hold.bookName.setText(Html.fromHtml(s));
        if (!DataUtil.isEmpty(data.getAuthorName())) {
            hold.auther.setVisibility(View.VISIBLE);
            hold.auther.setText(data.getAuthorName());
            UiUtil.setImgToTextView(context, R.drawable.res_search_auther_icon, hold.auther, 3);
        } else {
            hold.auther.setVisibility(View.INVISIBLE);
        }
        hold.auther.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Bundle bundle = new Bundle();
//                bundle.putString(Constant.BundleAuthorId, data.getAuthorid());
//                bundle.putString(Constant.BundleAuthorName, data.getAuthorName());
//                ARUtil.navigationFragment(RouterHub.HOME_AUTHOR, v, bundle);
            }
        });
        if (!DataUtil.isEmpty(data.getSummary())) {
            hold.bookIntro.setVisibility(View.VISIBLE);
            hold.bookIntro.setText(data.getSummary());
        } else {
            hold.bookIntro.setVisibility(View.INVISIBLE);
        }
        String classname = "";
        if (data.getCategoryNames() != null) {
            for (int i = 0; i < data.getCategoryNames().size(); i++) {
                if (!DataUtil.isEmpty(classname)) {
                    classname = classname + "  " + data.getCategoryNames().get(i).getClassName();
                } else {
                    classname = data.getCategoryNames().get(i).getClassName();
                }
            }
            hold.bookClass.setText(classname);
        } else {
            hold.bookClass.setText("");
        }

        hold.itemView.setOnClickListener(v -> {
//            Bundle bundle = new Bundle();
//            bundle.putString(Constant.BundleNovelid, data.getNovelid());
//            bundle.putString(Constant.BundleIsSearch, "1");
//            ARUtil.navigationFragment(RouterHub.READ_BOOKDETAIL, v, bundle);
        });
    }

    @Override
    public int getItemViewType(int position) {
        if (list.get(position).getAd() != null) {
            return AD_TYPR;
        }
        return LIST_TYPE;

    }

    class Hold extends RecyclerViewHolder {
        public Hold(int id, Context context) {
            super(id, context);
        }

        ImageView book;
        TextView bookName;
        TextView bookIntro;
        TextView auther;
        TextView bookClass;

        TextView tv_listitem_ad_source;
        TextView tv_listitem_ad_source1;
        TextView iv_listitem_dislike;
    }
}






